package com.flyxiaozhu.erp.core.stockrules;

import com.flyxiaozhu.erp.core.annotations.StockRule;
import com.flyxiaozhu.erp.core.entities.Goods;
import com.flyxiaozhu.erp.core.entities.GoodsOrder;
import com.flyxiaozhu.erp.core.entities.GoodsOrderDetail;
import com.flyxiaozhu.erp.core.entities.GoodsSku;
import com.flyxiaozhu.erp.core.libs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@StockRule
@Component
public class NormalRule implements IStockRule {
    @Autowired
    StockManager stockManager;

    @Override
    public int id() {
        return 1;
    }

    @Override
    public String name() {
        return "实物";
    }

    @Override
    public int type() {
        return Constants.GOODS_TYPE_REALITY;
    }

    @Override
    public JSONResult check(Goods goods, GoodsSku nullableSku, int num, HttpServletRequest request) {
        if (nullableSku != null) {
            if (nullableSku.getStock() < num) {
                return new JSONResult(ErrorCode.NO_STOCK, "库存不足");
            }
        } else {
            if (goods.getStock() < num) {
                return new JSONResult(ErrorCode.NO_STOCK, "库存不足");
            }
        }
        return new JSONResult();
    }

    @Override
    public JSONResult lockStock(GoodsOrder order, GoodsOrderDetail detail, Goods goods, GoodsSku nullableSku, HttpServletRequest request) throws AppException {
        return stockManager.lockStock(goods, detail, nullableSku, order);
    }

    @Override
    public JSONResult delivery(GoodsOrder order, GoodsOrderDetail detail, Goods goods, GoodsSku nullableSku, HttpServletRequest request) throws AppException {
        return new JSONResult().put("deliveryStatus", Constants.DELIVERY_STATUS_NORMAL);
    }

    @Override
    public void refund(GoodsOrder order, GoodsOrderDetail detail, Goods goods, GoodsSku nullableSku, HttpServletRequest request) throws AppException {
        stockManager.refundStock(goods, detail, nullableSku, order);
    }
}
